package com.xy.webadmin.app.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.xy.webadmin.app.constant.MqttConstants;
import com.xy.webadmin.app.model.MqttBrokerConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * MQTT HTTP API请求工具类
 *
 * @author xiaoyue
 * @date 2025-07-04
 */
@Slf4j
public class MqttApiUtil {
    
    /**
     * 执行对EMQX HTTP API的GET请求的通用方法
     *
     * @param config   MQTT配置，用于获取认证信息和URL
     * @param endpoint API端点 (例如 /stats)
     * @return 成功时返回响应体字符串，失败时返回null
     */
    public static String executeEmqxApiGetRequest(MqttBrokerConfig config, String endpoint) {
        try {
            if (config.getBrokerUrl() == null) {
                log.error("MQTT Broker URL为空，无法调用EMQX API");
                return null;
            }
            
            String baseApiUrl = extractHttpApiUrl(config.getBrokerUrl());
            String apiUrl = baseApiUrl + MqttConstants.ApiEndpoints.EMQX_API_BASE + endpoint;
            
            log.debug("调用EMQX API: GET {}", apiUrl);
            
            String username = config.getUsername() != null ? config.getUsername() : "";
            String password = config.getPassword() != null ? config.getPassword() : "";
            String authHeader = MqttConstants.Http.BASIC_AUTH_PREFIX + java.util.Base64.getEncoder()
                .encodeToString((username + ":" + password).getBytes());
            
            HttpResponse response = HttpRequest.get(apiUrl)
                .header(MqttConstants.Http.AUTH_HEADER, authHeader)
                .timeout(MqttConstants.ApiEndpoints.HTTP_TIMEOUT)
                .execute();
            
            if (response.isOk()) {
                String responseBody = new String(response.bodyBytes(), CharsetUtil.CHARSET_UTF_8);
                log.debug("EMQX API 响应 from {}: {}", apiUrl, responseBody);
                return responseBody;
            } else {
                log.error("EMQX API请求失败: {}, 状态码: {}, 响应: {}", apiUrl, response.getStatus(), response.body());
                return null;
            }
        } catch (Exception e) {
            log.error("调用EMQX API时发生异常 (endpoint: {}): {}", endpoint, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 从MQTT Broker URL中提取HTTP API URL
     *
     * @param brokerUrl MQTT Broker URL
     * @return HTTP API URL
     */
    private static String extractHttpApiUrl(String brokerUrl) {
        if (brokerUrl == null) {
            return "";
        }
        
        String url = brokerUrl;
        
        // 处理不同的协议前缀
        if (url.startsWith(MqttConstants.Url.TCP_PREFIX)) {
            url = MqttConstants.Http.HTTP_PREFIX + url.substring(MqttConstants.Url.TCP_PREFIX.length());
        } else if (url.startsWith(MqttConstants.Url.SSL_PREFIX)) {
            url = MqttConstants.Http.HTTPS_PREFIX + url.substring(MqttConstants.Url.SSL_PREFIX.length());
        } else if (url.startsWith(MqttConstants.Http.MQTT_PREFIX)) {
            url = MqttConstants.Http.HTTP_PREFIX + url.substring(MqttConstants.Http.MQTT_PREFIX.length());
        } else if (url.startsWith(MqttConstants.Http.MQTTS_PREFIX)) {
            url = MqttConstants.Http.HTTPS_PREFIX + url.substring(MqttConstants.Http.MQTTS_PREFIX.length());
        } else if (!url.startsWith(MqttConstants.Http.HTTP_PREFIX) && !url.startsWith(MqttConstants.Http.HTTPS_PREFIX)) {
            // 如果没有协议前缀，默认使用HTTP
            url = MqttConstants.Http.HTTP_PREFIX + url;
        }
        
        // 提取主机名和端口（如果有）
        String host;
        int port = MqttConstants.ApiEndpoints.EMQX_HTTP_PORT; // 默认EMQX HTTP API端口
        
        int portIndex = url.lastIndexOf(":");
        int slashAfterProtocol = url.indexOf("//");
        int nextSlash = url.indexOf("/", slashAfterProtocol + 2);
        
        if (nextSlash != -1) {
            // 去掉URL中的路径部分
            url = url.substring(0, nextSlash);
        }
        
        if (portIndex > slashAfterProtocol) {
            // URL中包含端口
            host = url.substring(0, portIndex);
            try {
                // 如果URL中的端口是MQTT端口，替换为HTTP API端口
                int urlPort = Integer.parseInt(url.substring(portIndex + 1));
                if (urlPort == MqttConstants.Url.DEFAULT_MQTT_PORT || urlPort == MqttConstants.Url.DEFAULT_MQTT_SSL_PORT) {
                    // 使用默认的HTTP API端口
                    if (url.startsWith(MqttConstants.Http.HTTPS_PREFIX)) {
                        port = MqttConstants.ApiEndpoints.EMQX_HTTPS_PORT; // HTTPS API端口
                    }
                } else {
                    // 保留原端口
                    port = urlPort;
                }
            } catch (NumberFormatException e) {
                log.warn("无法解析端口号: {}", url.substring(portIndex + 1));
            }
        } else {
            // URL中不包含端口
            host = url;
            if (url.startsWith(MqttConstants.Http.HTTPS_PREFIX)) {
                port = MqttConstants.ApiEndpoints.EMQX_HTTPS_PORT; // HTTPS API端口
            }
        }
        
        // 返回完整的HTTP API URL
        return host + ":" + port;
    }
} 